// services/menuService.ts
import { queryTreeList, menuAdd } from "@/api";
import type { MenuNode } from "@/types/menu";
import { ref } from "vue";

// 当前菜单树（单一数据源）
const menuTree = ref<MenuNode[]>([]);

// 是否已初始化
let isInitialized = false;

// 初始化菜单数据
async function init() {
  if (isInitialized) return;
  try {
    const res = await queryTreeList('menu');
    if (Array.isArray(res)) {
      menuTree.value = res[0].children;
    }
    isInitialized = true;
  } catch (error) {
    console.error("加载菜单失败", error);
    throw error;
  }
}

// 获取菜单树（供页面使用）
function getMenuTree() {
  return menuTree.value;
}

// 添加菜单
async function addMenu(parentId: string | null, menu: Omit<MenuNode, "id"> & { id?: string }) {
  const id = menu.id || `temp_${Date.now()}`;
  const newMenu: MenuNode = { id, ...menu };

  if (!parentId) {
    menuTree.value.push(newMenu);
  } else {
    const parent = findNodeById(menuTree.value, parentId);
    if (!parent.children) parent.children = [];
    parent.children.push(newMenu);
  }

  // 提交到后端
  try {
    await menuAdd(newMenu);
    // 后端返回真实 ID（如有）
  } catch (error) {
    // 回滚
    removeNodeById(menuTree.value, id);
    throw error;
  }
}

// 编辑菜单 
 
 

// 工具函数：查找节点
function findNodeById(tree: MenuNode[], id: string): MenuNode | null {
  for (const node of tree) {
    if (node.id === id) return node;
    if (node.children) {
      const found = findNodeById(node.children, id);
      if (found) return found;
    }
  }
  return null;
}

// 工具函数：删除节点
function removeNodeById(tree: MenuNode[], id: string): boolean {
  for (let i = 0; i < tree.length; i++) {
    if (tree[i].id === id) {
      tree.splice(i, 1);
      return true;
    }
    if (tree[i].children) {
      if (removeNodeById(tree[i].children, id)) return true;
    }
  }
  return false;
}

// 工具函数：插入节点（用于回滚）
function insertNode(tree: MenuNode[], node: MenuNode): boolean {
  if (node.children) node.children = [...node.children];
  if (!node.parentId) {
    tree.push(node);
    return true;
  }
  const parent = findNodeById(tree, node.parentId);
  if (parent) {
    if (!parent.children) parent.children = [];
    parent.children.push(node);
    return true;
  }
  return false;
}

export const menuService = {
  init,
  getMenuTree,
  addMenu,
  findNodeById,
};